package com.example.studentmanagersystem;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;

import com.fs.po.Classes;
import com.fs.utils.CmdUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * teacher Info update page
 * @author chenwenfei
 *
 */
public class TeacherInfoChangeActivity extends Activity {
	
	private EditText nameET,passwordET,ageET,phoneET;
	private Spinner classSpinner;
	private RadioGroup sexRadio;
	private Button submit,actionBack,actionMenu;
	private ArrayAdapter<String> adapter;
	
	private String name;
	private String password;
	private int age;
	private String phone;
	private String sex;
	
	private int index;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.teacher_personal_infochange_activity);
		
		this.getData("tec_get_classes");
		
		this.init();
	}
	
	
	String[] className;
	String[] classId;
	List<String> c_name;
	List<String> c_id;
	Handler handler=new Handler(){
		
		public void handleMessage(Message msg) {
			
			c_name=new ArrayList<String>();
			c_id=new ArrayList<String>();
			
			List<Classes> classList=(List<Classes>) msg.obj;
			
			
			
			for(int i=0;i<classList.size();i++){
				
				c_name.add(classList.get(i).getName());
				c_id.add(""+classList.get(i).getClass_id());
				
			}
			
			className=new String[c_name.size()];
			classId = new String[c_id.size()];
			className=c_name.toArray(className);
			classId=c_id.toArray(classId);
			
			setListener();
			
		};
		
	};
	
	/**
	 * initialize widget
	 */
	private void init() {
		
		this.actionBack=(Button) this.findViewById(R.id.tecInfo_action_backButton);
		this.actionMenu=(Button) this.findViewById(R.id.tecInfo_action_menu);
		
		this.nameET=(EditText) this.findViewById(R.id.teacher_info_name_et);
		this.passwordET=(EditText) this.findViewById(R.id.teacher_info_password_et);
		this.ageET=(EditText) this.findViewById(R.id.teacher_info_age_et);
		this.phoneET=(EditText) this.findViewById(R.id.teacher_info_phone_et);
		this.submit=(Button) this.findViewById(R.id.teacher_info_updateSubmit);
		this.sexRadio=(RadioGroup) this.findViewById(R.id.teacher_info_sexRadio);
		this.classSpinner=(Spinner) this.findViewById(R.id.teacher_info_class_spinner);
		
		

	}
	
	/**
	 * spinner listener
	 */
	private void setListener() {
		
		adapter = new ArrayAdapter<String>(TeacherInfoChangeActivity.this,android.R.layout.simple_list_item_single_choice, className);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		classSpinner.setAdapter(adapter);
		
		 
		this.classSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				
				index=arg2;
				
			}
			

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		
		
		});
		
		this.sexRadio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				 
				if(checkedId==R.id.teacher_info_sex_nam){
					
					sex="nam";
					
				}else if(checkedId==R.id.teacher_info_sex_women){
					
					sex="women";
					
				}
				
			}
		});
		
		this.submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				getChangeInfo();
			}
		});
		
		//back listener
		this.actionBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				TeacherInfoChangeActivity.this.finish();
			}
		});
		
		//menu listener
		this.actionMenu.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				PopupMenuUtil popupMenuUtil=new PopupMenuUtil(v,TeacherInfoChangeActivity.this);
				popupMenuUtil.actionBackListener();
				
			}
		});

	}
	
	
	/**
	 * get update info that you will change
	 */
	private void getChangeInfo() {

		boolean isName=TextUtils.isEmpty(nameET.getText());
		boolean isPassword=TextUtils.isEmpty(passwordET.getText());
		boolean isAge=TextUtils.isEmpty(ageET.getText());
		boolean isPhone=TextUtils.isEmpty(phoneET.getText());
		boolean isSex=TextUtils.isEmpty(sex);
		
		if(!(isName&&isPassword&&isAge&&isPhone&&isSex)){
			
			this.name=nameET.getText().toString().trim();
			this.password=passwordET.getText().toString().trim();
			this.age=Integer.parseInt(ageET.getText().toString().trim());
			this.phone=phoneET.getText().toString().trim();
			
			showNormalDia();
			
			
		}
	}
	
	
/**
 * get all classes from service	
 * @param action
 */
	
private void getData(String action) {
		
		RequestParams params = new RequestParams();
		
		params.addBodyParameter("action", action);
		
		HttpUtils httpUtils=new HttpUtils();
		
		httpUtils.send(HttpMethod.POST, URL.SOCRE_URL, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

				String jsonString=responseInfo.result;
				
				setClassData(jsonString);
				
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				
			}

		});
	}
	
	
	
/**
 * 解析数据
 * @param jsonString
 * @return
 */
	List<Classes> classList;
	
	private void setClassData(String jsonString) {
		
		classList=new ArrayList<Classes>();
		
		Classes classes=null;
			if(jsonString!=null){
				
				try {
					
					JSONObject jsonObject = new JSONObject(jsonString);
					
					JSONArray array=jsonObject.getJSONArray("class");
					
					for(int i=0;i<array.length();i++){
						JSONObject json=array.getJSONObject(i);
						
						int class_id=Integer.parseInt(json.getString("_id"));
						
						String class_name=json.getString("class_name");
						
						classes=new Classes(class_id, class_name);

						classList.add(classes);
					}

					new Thread(){
						
						@Override
						public void run() {
							super.run();
							
							Message msg=Message.obtain();
							
							msg.obj=classList;
							handler.sendMessage(msg);
						}
						
					}.start();
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
			
		}
	
	
	
	/**
	 * show dialog
	 */
	  private void showNormalDia(){  
	        //AlertDialog.Builder normalDialog=new AlertDialog.Builder(getApplicationContext());  
	        AlertDialog.Builder normalDia=new AlertDialog.Builder(this);  
	        normalDia.setIcon(R.drawable.sure);  
	        normalDia.setTitle("提示");  
	        normalDia.setMessage("确定添加？");  
	          
	        normalDia.setPositiveButton("确定", new DialogInterface.OnClickListener() {  
	            @Override  
	            public void onClick(DialogInterface dialog, int which) {
	            	
	            	int class_id=Integer.parseInt(classId[index]);
	    			
	    			String cmd="update tec set name='"+name+"',password='"+password+"',age="+age+",sex='"+sex+"',class_id="+class_id+",tel='"+phone+"' where _id="+MainActivity._id+"";
	    			
	    			CmdUtils cmdUtils=new CmdUtils(TeacherInfoChangeActivity.this);
	    			
	    			cmdUtils.submitCmd(URL.CMD_URL,"update",cmd);
	    			
	    			TeacherInfoChangeActivity.this.finish();
	                
	            }  
	        });  
	        
	        normalDia.setNegativeButton("取消", new DialogInterface.OnClickListener() {  
	            @Override  
	            public void onClick(DialogInterface dialog, int which) {  
	               
	            }  
	        });  
	        normalDia.create().show();  
	    } 
	
	
}
